package com.remon.quartz.filter;

import com.alibaba.fastjson.JSON;
import github.remonlong.restfulutil.exception.RestfulResultUtil;
import github.remonlong.restfulutil.exception.api.BadApiException;
import github.remonlong.restfulutil.exception.enumeration.EnumResult;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * jwt 过滤器
 *
 * @author remon
 * @create 2018-08-16 0:14
 **/
public class JwtFilter extends GenericFilterBean {

    @Override
    public void doFilter(final ServletRequest req,
                         final ServletResponse res,
                         final FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        //客户端将token封装在请求头中，格式为（Bearer后加空格）：Authorization：Bearer +token
        final String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            //"Missing or invalid Authorization header."
//            throw new BadApiException(EnumResult.PARAM_VALID_ERROR);
            res.setCharacterEncoding("UTF-8");
            res.getWriter().print(JSON.toJSONString(RestfulResultUtil.error(EnumResult.VALIDATION_ROLE)));
            res.flushBuffer();
            return;
        }
        //去除Bearer 后部分
        final String token = authHeader.substring(7);
        try {
            //解密token，拿到里面的对象claims
            final Claims claims = Jwts.parser().setSigningKey("421321321")
                    .parseClaimsJws(token).getBody();
            //将对象传递给下一个请求
            request.setAttribute("claims", claims);
        } catch (final SignatureException e) {
            //throw new BadApiException(EnumResult.PARAM_VALID_ERROR);
            res.setCharacterEncoding("UTF-8");
            res.getWriter().print(JSON.toJSONString(RestfulResultUtil.error(EnumResult.LOGIN_TIMEOUT)));
            res.flushBuffer();
            return;
        }
        chain.doFilter(req, res);
    }

}